<?php
#
#	plugin class for LemurCMS
#
#
if(class_exists('init')) {
	$initClass = new init(false);
	$initClass->getPluginList();
}
$pluginList = array(
	'scripts' => array(),
	'styles' => array('attachMessageCSS'),
	'beforeBodyEnd' => array(),
	'search' => array(),
	'search-box' => array()
);
$pluginInterfaceList = array();
function plugin ($location, $data = array()) {
	global $pluginList;

	if( empty($pluginList[ $location ]) ) return;
	$plugins = $pluginList[ $location ];
	if( empty($plugins) ) return;

	foreach( $plugins as $pFunc ) {
		if( is_callable( $pFunc ) )
		call_user_func_array( $pFunc, (array)$data );
	}
}
function registerPlugin( $pLocation, $pName ) {
	global $pluginList;
	if( !isset($pluginList[ $pLocation ]) ) {
		$pluginList[ $pLocation ] = array();
	}
	$pluginList[ $pLocation ] = array_merge( (array)$pluginList[ $pLocation ], (array)$pName );
}
function runInterface( $title) {
	global $pluginInterfaceList;
	if(array_key_exists( $title, (array) $pluginInterfaceList) &&  is_callable( $pluginInterfaceList[$title] ))
		call_user_func( $pluginInterfaceList[$title]);
}
function runInstall ( $plugin ) {
	global $pluginInstall;
	if( is_callable( $pluginInstall[$plugin] ) )
		call_user_func( $pluginInstall[$plugin] );
}
function runUninstall ( $plugin ) {
	global $pluginUninstall;
	if( is_callable( $pluginUninstall[$plugin] ) )
		call_user_func( $pluginUninstall[$plugin] );
}
$optionsRun = false;
class Plugin extends functions {
	public $pluginName;
	public $visName;
	public $Interface;
	public $isActive = false;
	public $options = false;
	public $SERVER_ROOT = BASE_URL, $VISUAL_ROOT = THEME_URL;
	
	public function Plugin( $pN ) {
		if($pN !== false) {
			global $initClass;
			global $pluginData;
			$activePlugins = $initClass->activePlugins;
			$this->pluginName = $this->make_clean_url($pN);
			$pluginData[ $this->pluginName ][ 'name' ] = $pN;
			$this->visName = $pN;
			if( in_array($this->visName, (array)$activePlugins ) ) {
				$this->isActive = true;
			}
			else {
				$this->isActive = false;
			}
		}
	}
	public function addPlugin( $location, $callFunction ) {
		global $initClass;
		global $pluginList;
		if( !isset($pluginList[ $pLocation ]) ) {
			$pluginList[ $pLocation ] = array();
		}
		if( !$this->isActive ) return;
		if( empty($this->pluginName) )
		$page->message('Error', 'Plugin Error', 'Plugin Name not specified');

		global $pluginData;
		$pluginData[ $this->visName ][ 'plugins' ][] = array( 'location'=>$location , 'callFunction'=>$callFunction );
 		if(array_key_exists($this->visName , $initClass->dbPluginList)) {
			
		}
		else {
			$options = serialize(array('active'=>'no'));
			$sql = "INSERT INTO ".DBTABLEPREFIX."plugins (name, options) VALUES ('{$pluginData[ $this->visName ][ 'name' ]}', '{$options}')";
			$query = $this->db_query($sql) or die($this->message('error', 'MySQL Error', $this->db->error()));
		}
		registerPlugin( $location, $callFunction );
	}
	public function description( $desc ) {
		global $pluginData;
		$pluginData[ $this->pluginName ][ 'desc' ] = $desc;
	}
	public function version( $desc ) {
		global $pluginData;
		$pluginData[ $this->pluginName ][ 'version' ] = $desc;
	}
	public function author( $auth ) {
		global $pluginData;
		$pluginData[ $this->pluginName ][ 'author' ] = $auth;
	}
	public function addUninstall ( $func ) {
		global $pluginUninstall;
		$pluginUninstall [ $this->visName ] = $func;
	}
	public function addInstall ( $func ) {
		global $pluginInstall;
		$pluginInstall [ $this->visName ] = $func;
	}
	public function addInterface( $interfaceFunc ) {
		global $pluginData;
		global $pluginInterfaceList;
		$pluginInterfaceList[$this->pluginName] = $interfaceFunc;
		$pluginData[ $this->pluginName ][ 'interface' ] = $interfaceFunc;
	}
		// Format for adding page
		// @param str: page title
		// @param str: menu title
		// @param str: content
		// @param str: weight
		// @param str: parent_id
		// @param str: secondary		
		// @param str: options
		//
	public function addPage ($pageTitle, $menuTitle, $content, $weight = '0', $parentId = '0', $secondary = '', $options = 'a:0:{}') {
		if(is_array($options))
			$options = serialize($options);
		$pageTitle = addslashes($pageTitle);
		$menuTitle = addslashes($menuTitle);
		$content = addslashes($content);
		$options = addslashes($options);
		$sql = "INSERT INTO ".DBTABLEPREFIX."content_pages (title, content, orderingid, menutitle, parent_id, time, secondary, options)
					VALUES ('$pageTitle', '$content', '$weight', '$menuTitle', '$weight', '$parentId', '$secondary', '$options')";
		$query = $this->db->query($sql) or die($this->db->error());
	}
	public function addOption ($name, $value) {
		$plugin = $this->visName;
		if(!$this->getOption($plugin, $name)) {
			$name = addSlashes($name);
			$plugin = addSlashes($plugin);
			if(is_array($value))
				$value = serialize($value);
			$value = addSlashes($value);
			$sql = "INSERT INTO ".DBTABLEPREFIX."plugins_settings (plugin, field_name, data)
			VALUES ('$plugin', '$name', '$value')";
			$query = $this->db_query($sql);
			return $query;
		}
		else {
			return true;
		}
	}
	public function updateOption ($name, $value) {
		global $allOptions;
		$plugin = $this->visName;
		$this->getAllOptions();
		$name = addSlashes($name);
		$plugin = addSlashes($plugin);
		if(is_array($value))
			$value = serialize($value);
		$value = addSlashes($value);
		if(array_key_exists($name, (array) $allOptions[$plugin]))
			$sql = "UPDATE ".DBTABLEPREFIX."plugins_settings SET data = '{$value}' WHERE plugin = '{$plugin}' AND field_name = '{$name}'";
		else
			$sql = "INSERT INTO ".DBTABLEPREFIX."plugins_settings (plugin, field_name, data) VALUES ('{$plugin}', '{$name}', '{$value}')";
		$query = $this->db_query($sql) or die($this->db->error());
		$this->getAllOptions(true);
		return $query;
	}
	public function deleteOption ($name) {
		$plugin = $this->visName;
		$sql = "DELETE FROM ".DBTABLEPREFIX."plugins_settings WHERE plugin = '{$plugin}' AND field_name = '{$name}'";
		$query = $this->db_query($sql);
		return $query;
	}
	public function getOption ($name) {
		global $optionsRun, $allOptions;
		$plugin = $this->visName;
		if(empty($allOptions)) {
			$this->getAllOptions();
		}
		if(array_key_exists($name, (array) $allOptions[$plugin]))
			return $allOptions[$plugin][$name];
		else
			return false;
	}
	public function getAllOptions ($reset = false) {
		global $optionsRun, $allOptions;
		$plugin = $this->visName;
			if($optionsRun == false || $reset == true) {
			$sql = "SELECT * FROM ".DBTABLEPREFIX."plugins_settings";
			$query = $this->db_query($sql) or die($this->db->error());
			while($row = $this->db->fetchAssoc($query)) {
				foreach($row as $key => $value) {
					$row[$key] = stripcslashes(stripcslashes($value));
				}
//				var_dump($row);
				if(unserialize($row['data']))
					$allOptions[$row['plugin']][$row['field_name']] = unserialize($row['data']);
				else
					$allOptions[$row['plugin']][$row['field_name']] = stripcslashes(stripcslashes($row['data']));
			}
			$optionsRun = true;
		}
		if($allOptions !== false)
			return $allOptions[$plugin];
		else
			return false;
	}
	public function addSidebarBlock ($title, $func) {
		global $pluginData;
		$pluginData[$this->pluginName][ 'sidebar' ][] = array( 'title'=>$title, 'callFunction'=>$func );		
	}
	public function addDashboardBlock ($title, $func, $column = '1') {
		global $pluginData;
		$pluginData[ 'dashboard' ][] = array( 'title'=>$title, 'callFunction'=>$func , 'column' =>$column);		
	}
	public function addPermission ($name, $value) {
		$perUrl = BASE_URL.'includes/admin/permissions.php';
		$per = unserialize(file_get_contents($perUrl));
		foreach($per as $level => $arrtrue) {
			foreach($arrtrue as $cat => $arr2) {
				if($cat == 'Individual Actions') {
					//var_dump($newPer[$level][$cat]);
					$per[$level][$cat][$name] = (bool) $value;
				}
			}
		}
		file_put_contents($perUrl, serialize($per));
	}
	public function updatePermission ($name, $value) {
		$this->addPermission($name, $value);
	}
	public function removePermission ($name) {
		$perUrl = BASE_URL.'includes/admin/permissions.php';
		$per = unserialize(file_get_contents($perUrl));
		foreach($per as $level => $arrtrue) {
			foreach($arrtrue as $cat => $arr2) {
				if($cat == 'Individual Actions') {
					unset($per[$level][$cat][$name]);
				}
			}
		}
		file_put_contents($perUrl, serialize($per));
	}
	/*
		Message Functions
	*/
		public function message($type = 'message', $header = "", $content = "", $small = false) {
			$r .= "<div class='message-wrapper";
			if($small == true) {
				$r .= ' message-small';
			}
			else {
				$r .= ' message-large';
			}
			$r .= "'>";
			switch ($type) {
				case 'message':
					$r .= "<div class='message-message message'>\n\t<div class='message-message-header message-header'>".$header."</div>\n\t<div class='message-message-content message-content'>\n\t\t<p>".$content."</p>\n\t</div>\n</div>";
					break;
				case 'success':
					$r .= "<div class='message-ok message'>\n\t<div class='message-ok-header message-header'>".$header."</div>\n\t<div class='message-ok-content message-content'>\n\t\t<p>".$content."</p>\n\t</div>\n</div>";
					break;
				case 'error':
					$r .= "<div class='message-error message'>\n\t<div class='message-error-header message-header'>".$header."</div>\n\t<div class='message-error-content message-content'>\n\t\t<p>".$content."</p>\n\t</div>\n</div>";
					break;
				case 'warning':
					$r .= "<div class='message-warning message'>\n\t<div class='message-warning-header message-header'>".$header."</div>\n\t<div class='message-warning-content message-content'>\n\t\t<p>".$content."</p>\n\t</div>\n</div>";
					break;
			}
			$r .= "</div>";
			return $r;
		}
}
function attachMessageCSS () {
	echo '<style type="text/css">@import "'.THEME_URL.'includes/admin/css/messages.css";</style>
';
}
?>